import abc

import pymysql

from com.cqt.tools.mysql.JavaModel import JavaModel
from com.cqt.tools.mysql.table_fields import TableField, Table


class db:

    @abc.abstractmethod
    def get_conn(self):
        pass

    def __init__(self):
        # 替换以下参数为你的数据库实际信息
        self._connection = None
        self._cursor = None

    def fetch_one_sql(self, sql, params=None):
        try:
            self.get_conn()
            self._cursor = self._connection.cursor()
            self._cursor.execute(sql, params or ())
            return self._cursor.fetchone()
        except Exception as e:
            print(e)
            return None
        finally:
            self.close()

    def fetch_all_sql(self, sql, params=None):
        try:
            self.get_conn()
            self._cursor = self._connection.cursor()
            self._cursor.execute(sql, params or ())
            return self._cursor.fetchall()
        except Exception as e:
            print(e)
            return None
        finally:
            self.close()

    def show_tables(self, sql="show tables"):
        rs = self.fetch_all_sql(sql)
        if rs is not None:
            tables = []
            for r in rs:
                tables.append(r[0])
            return tables
        return rs

    def desc_table(self, tableName):
        rs = self.fetch_all_sql("SHOW FULL COLUMNS FROM  " + tableName)
        if rs is not None:
            tables = []
            for r in rs:
                f = TableField()
                tables.append(f.build(r))
            table = Table(tables)
            rs = self.fetch_all_sql("SHOW create table   " + tableName)
            table.build(rs)
            return table
        return rs

    def close(self):
        """安全关闭数据库连接"""
        if self._cursor:
            self._cursor.close()
            self._cursor = None
        if self._connection:
            self._connection.close()
            self._connection = None


class dev_db(db):

    def get_conn(self):
        self._connection = pymysql.connect(host="10.255.1.26",  # 数据库地址
                                           port=3300,
                                           user="root",  # 用户名
                                           password="cqt@1234",  # 密码
                                           database="boss-platform-charge",  # 数据库名
                                           charset='utf8mb4')  # 字符集，根据需要选择


db_util = dev_db()

rs = db_util.show_tables()
for tableName in rs:
    if tableName == 'charge_supplier_account_bill_detail':
        table = db_util.desc_table(tableName=tableName)
        jm = JavaModel(table)
        #jm.echoJava()
        jm.echoJavaFile(javaName="SupplierAccountBillDetailDO"
                        ,packageName="com.linkcircle.boss.module.report.web.bill.model.entity",
                        baseDir=r"D:\workspace\boss-platform\boss-platform-service\boss-platform-service-charge-report\src\main\java")
